import { Result } from './common'
import { ApiBaseError } from "./error";
import { parseTime, writeAppendFile } from './utils'
import path from 'path'

export class Log {
  // 日志目录
  static LOG_PATH = path.resolve(__dirname, '../../../log')

  // 错误日志文件名
  static ERROR_LOG_FILENAME = 'error-log.log'

  // 打印日志文件名
  static PRINT_LOG_FILENAME = 'print-log.log'

  // 错误
  static error(error: Result | ApiBaseError | Error) {
    // 当前时间
    const now = Date.now()
    // 错误信息
    let errLog = ''
    if (error instanceof Result) {
      errLog = `
${now}
---------------------------------------------------------------
错误时间: ${parseTime(now)}\n
错误代码: ${error.code}\n
错误信息: ${error.msg}
---------------------------------------------------------------
`
    } else if (error instanceof ApiBaseError) {
      errLog = `
${now}
---------------------------------------------------------------
错误时间: ${parseTime(now)}\n
错误代码: ${error.errCode}\n
错误信息: ${error.errMsg}
---------------------------------------------------------------
`
    } else if (error instanceof Error) {
      errLog = `
${now}
---------------------------------------------------------------
错误时间: ${parseTime(now)}\n
错误名称: ${error.name}\n
错误信息: ${error.message}\n
错误堆栈: ${error.stack}
---------------------------------------------------------------
`
    }    

    writeAppendFile(Log.LOG_PATH, Log.ERROR_LOG_FILENAME, errLog)
  }

  // 打印
  static print(val:any) {
    // 当前时间
    const now = Date.now()
    // 打印内容
    const printLog = `
${now}
---------------------------------------------------------------
打印时间: ${parseTime(now)}\n
打印内容: ${val.toString()}
---------------------------------------------------------------
`
    writeAppendFile(Log.LOG_PATH, Log.PRINT_LOG_FILENAME, printLog)
  }
} 